package com.example.util;
import java.io.InputStream;
import java.io.Writer;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;


public class MapUtil {
	/**
	 * 解析微信发来的请求（XML
	 * @param request 
	 * @return
	 * @throws Exception
	 */
	public static Map<String,Object>parseXml(HttpServletRequest request)throws Exception{
		//将解析结果存储在HashMap中 
		Map<String,Object>map=new HashMap<String,Object>();
		//从request中取得输入流 
		InputStream inputStream=request.getInputStream();
		//读取输入流
		SAXReader reader=new SAXReader();
		Document document=reader.read(inputStream);
		//得到xml根元素 
		Element root=document.getRootElement();
		//得到根元素的所有子节点 
		List<Element>elementList=root.elements();
		//遍历所有子节点   
		for(Element e:elementList){
			map.put(e.getName(),e.getText());
		}
		//释放资源
		inputStream.close();
		inputStream=null;
		return map;
	}
	
	/**
	 * 解析微信发来的请求（XML
	 * @param request 
	 * @return
	 * @throws Exception
	 */
	public static Map<String,Object>parseXml(String xml)throws Exception{
		//将解析结果存储在HashMap中 
		Map<String,Object>map=new HashMap<String,Object>();
		Document doc =   DocumentHelper.parseText(xml);; 
        Element root = doc.getRootElement(); 
        //得到根元素的所有子节点 
		List<Element>elementList=root.elements();
		//遍历所有子节点   
		for(Element e:elementList){
			map.put(e.getName(),e.getText());
		}
		return map;
	}
	/**将url和参数拼接好
	 * @param url
	 * @param param
	 * @return
	 */
	public static String getSpellUrl(String url,String []param){
		String resultUrl=url;
		for(int i=0;i<param.length;i++){
			resultUrl=resultUrl.replace("{"+i+"}",param[i]);
		}
		return resultUrl;
	}
	public static String getConfigProperty(String configPath,String propertyName) throws ConfigurationException{
		Configuration config =  new PropertiesConfiguration(configPath);
		String rs = config.getString(propertyName);
		return rs;
	}
	public static String getConfigValue(String key){
		try {
			return getConfigProperty("config.properties",key);
		} catch (ConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
